import torch
import torch.nn as nn
import torch.optim as optim
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

print("cuda is available:")
print(torch.cuda.is_available())
print("\n")

# 设置随机种子确保可复现性
torch.manual_seed(42)
np.random.seed(42)

# 加载数据集 - 使用您指定的URL和列名
print("正在加载数据集...")
url = 'https://gairuo.com/file/data/dataset/iris.data'
iris = pd.read_csv(url, header=0,
                 names=['萼片长度', '萼片宽度', '花瓣长度', '花瓣宽度', '品种'])

# 显示数据集信息
print("\n数据集信息:")
print(f"样本数量: {len(iris)}")
print(f"特征列: {iris.columns[:4].tolist()}")
print(f"品种分布:\n{iris['品种'].value_counts()}")

# 将品种名称映射为数字标签
variety_mapping = {
    'setosa': 0,
    'versicolor': 1,
    'virginica': 2
}
iris['品种'] = iris['品种'].map(variety_mapping)


# 准备数据
X = iris[['萼片长度', '萼片宽度', '花瓣长度', '花瓣宽度']].values
y = iris['品种'].values

# 数据预处理
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(
    X_scaled, y, test_size=0.2, random_state=42
)

# 转换为PyTorch张量
X_train_tensor = torch.tensor(X_train, dtype=torch.float32)
y_train_tensor = torch.tensor(y_train, dtype=torch.long)
X_test_tensor = torch.tensor(X_test, dtype=torch.float32)
y_test_tensor = torch.tensor(y_test, dtype=torch.long)

# 定义Softmax回归模型
class SoftmaxRegression(nn.Module):
    def __init__(self, input_dim, output_dim):

        """
        Softmax回归模型
        
        参数:
        input_dim: 输入特征维度
        output_dim: 输出类别数
        """
        super(SoftmaxRegression, self).__init__()
        # 线性层 (输入特征数 -> 输出类别数)
        self.linear = nn.Linear(input_dim, output_dim)
    
    def forward(self, x):
        # 返回线性层的输出
        return self.linear(x)
    
    def predict_proba(self, x):
        """预测概率分布"""
        # 对输出应用softmax得到概率
        logits = self.forward(x)
        return nn.functional.softmax(logits, dim=1)
    
    def predict(self, x):
        """预测类别"""
        logits = self.forward(x)
        return torch.argmax(logits, dim=1)
    
    def accuracy(self, x, y):
        """计算准确率"""
        preds = self.predict(x)
        return torch.mean((preds == y).float()).item()

# 训练参数
input_dim = X_train.shape[1]  # 4个特征
output_dim = len(np.unique(y))  # 3个类别
learning_rate = 0.1
num_epochs = 500
batch_size = 16

# 初始化模型
model = SoftmaxRegression(input_dim, output_dim)

# 损失函数和优化器
criterion = nn.CrossEntropyLoss()  # 包含softmax的交叉熵损失
optimizer = optim.SGD(model.parameters(), lr=learning_rate)

# 训练模型
print("\n开始训练模型...")
train_losses = []
train_accuracies = []
test_accuracies = []

for epoch in range(num_epochs):
    # 随机打乱数据
    indices = torch.randperm(X_train_tensor.size(0))
    X_shuffled = X_train_tensor[indices]
    y_shuffled = y_train_tensor[indices]
    
    epoch_loss = 0.0
    correct = 0
    total = 0
    
    # 小批量训练
    for i in range(0, X_train_tensor.size(0), batch_size):
        # 获取小批量数据
        end_idx = min(i + batch_size, X_train_tensor.size(0))
        inputs = X_shuffled[i:end_idx]
        labels = y_shuffled[i:end_idx]
        
        # 前向传播
        outputs = model(inputs)
        loss = criterion(outputs, labels)
        
        # 反向传播和优化
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        
        # 记录损失和准确率
        epoch_loss += loss.item() * inputs.size(0)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()
    
    # 计算训练损失和准确率
    train_loss = epoch_loss / X_train_tensor.size(0)
    train_accuracy = correct / total
    
    # 计算测试集准确率
    with torch.no_grad():
        test_accuracy = model.accuracy(X_test_tensor, y_test_tensor)
    
    # 记录指标
    train_losses.append(train_loss)
    train_accuracies.append(train_accuracy)
    test_accuracies.append(test_accuracy)
    
    # 每50个epoch打印一次
    if (epoch + 1) % 50 == 0:
        print(f'Epoch [{epoch+1}/{num_epochs}], '
              f'Train Loss: {train_loss:.4f}, '
              f'Train Acc: {train_accuracy:.4f}, '
              f'Test Acc: {test_accuracy:.4f}')

# 最终评估
with torch.no_grad():
    train_acc = model.accuracy(X_train_tensor, y_train_tensor)
    test_acc = model.accuracy(X_test_tensor, y_test_tensor)
    print(f'\n最终模型性能:')
    print(f'训练准确率: {train_acc:.4f}')
    print(f'测试准确率: {test_acc:.4f}')

# 可视化训练过程
plt.figure(figsize=(12, 4))

# 损失曲线
plt.subplot(1, 2, 1)
plt.plot(train_losses, label='训练损失')
plt.title('训练损失变化')
plt.xlabel('训练轮次')
plt.ylabel('损失')
plt.legend()

# 准确率曲线
plt.subplot(1, 2, 2)
plt.plot(train_accuracies, label='训练准确率')
plt.plot(test_accuracies, label='测试准确率')
plt.title('准确率变化')
plt.xlabel('训练轮次')
plt.ylabel('准确率')
plt.legend()

plt.tight_layout()
plt.savefig('softmax_training.png', dpi=300)
plt.show()

# 预测示例
sample_idx = 10
sample = X_test_tensor[sample_idx].unsqueeze(0)  # 添加批次维度
with torch.no_grad():
    proba = model.predict_proba(sample)
    prediction = model.predict(sample)

# 反向映射品种名称
reverse_mapping = {v: k for k, v in variety_mapping.items()}

print(f"\n样本真实类别: {reverse_mapping[y_test[sample_idx]]}")
print(f"预测类别: {reverse_mapping[prediction.item()]}")
print("各类别概率:")
for i, prob in enumerate(proba.squeeze().numpy()):
    print(f"{reverse_mapping[i]}: {prob:.4f}")

# 保存模型
torch.save(model.state_dict(), 'softmax_regression_model.pth')
print("\n模型已保存为 'softmax_regression_model.pth'")